import { reactive, toRefs, computed } from "vue"
import { onShow, onUnload, onReady, onLoad } from "@dcloudio/uni-app";
/**
 * @description  文件上传
 * @param rules 表单校验规则
 * */
export const useUploadFile = () => {
	const state = reactive({})
	// 上传图片文件
	const uploadFile = async (filePath, path, type, data) => {
		uni.showLoading({
			title: "加载中..."
		});
		const fileIDs = []
		function generateUniqueFileName() {
			return Date.now().toString() + Math.random().toString(36).substr(2, 6);
		}
		for (let item of filePath) {
			const res = await uniCloud.uploadFile({
				cloudPathAsRealPath: true,
				filePath: item.path,
				cloudPath: `/${path}/` + `${path}_${generateUniqueFileName()}.jpg`,
			})
			if (type == 'url') {
				fileIDs.push(res)
			} else {
				if (res.filePath == item.path) {
					// const img = await api.method(res.fileID)
					// if (!img.success) {
					// 	uni.fui.toast(img.errMsg)
					// 	deleteFile([{filePath:res.filePath,fileID:img.url}],res.filePath)
					// } else {
						item.path = res.fileID
						item.url = res.fileID
						item.fileID = res.fileID
						item.filePath = res.filePath
						delete item.file
						fileIDs.push(item)
					// }
				}
			}

		}
		uni.hideLoading();
		return fileIDs
	}

	/***
	 * @description: 删除上传的文件
	 * @param {*}
	 * @return {*}
	 * @author: white_queen
	 */
	const deleteFile = async (fileIDs, filePath) => {
		const fileList = fileIDs.filter(item => item.filePath === filePath.tempFilePath).map(item => item
			.fileID);
		const api = uniCloud.importObject('qc-global', { customUI: true })
		await api.deleteFileApp({ fileList })
		console.log("执行了");
	}

	/***
	 * @description: 获取编译后的file文件信息
	 * @param {*}
	 * @return {*}
	 * @author: white_queen
	 */
	const getFileInfo = async (fileIDs) => {
		const fileLists = fileIDs.map(item => item.fileID);
		return new Promise((resolve, reactive) => {
			setTimeout(async () => {
				try {
					const res = await uniCloud.getFileInfo({ fileList: fileLists })
					resolve(res)
				} catch (e) {
					reactive(e)
				}
			}, 2000)
		})

	}

	return {
		uploadFile,
		deleteFile,
		getFileInfo
	};
}